<template>
  <BasicDrawer
    v-bind="$attrs"
    @register="registerDrawer"
    showFooter
    :title="getTitle"
    width="500px"
    @ok="handleSubmit"
  >
    <BasicForm @register="registerForm">
      <template #relateCode="{ model, field }">
        <Select
          :options="moduleList"
          v-model:value="model[field]"
          placeholder="请选择"
          style="width: 100%"
          showSearch
          :disabled="isUpdate"
          optionFilterProp="name"
          :field-names="{ label: 'name', value: 'code' }"
          @change="handleChangeRelateCode"
        />
      </template>
      <template #conds>
        <a-button
          :type="dataRef.conds && dataRef.conds.length ? 'primary' : 'default'"
          @click="handleConfiguration"
          title="当满足条件时，显示选项卡"
        >
          配置
        </a-button>
      </template>
    </BasicForm>
    <div class="mt-2">
      '注： 所选从模块的字段cws_id默认等于本模块id字段 ，关联方式：表单型（单个记录）暂不支持'
    </div>
    <ConfigurationModal
      @register="registerConfigurationModal"
      @success="handleSuccessConfigurationModal"
    />
  </BasicDrawer>
</template>
<script lang="ts">
  import { defineComponent, ref, computed, unref, onMounted } from 'vue';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { formSchema, otherFormFields } from './relateComponent.data';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import { useModal } from '/@/components/Modal';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { getFormGetFields } from '/@/api/flowManage/flowManage';
  import { Select } from 'ant-design-vue';
  import ConfigurationModal from '../configuration/index';
  import { getVisualGetFormFieldsWithModuleRelated } from '/@/api/module/module';
  import { getModulesAll } from '/@/api/system/system';
  import { getVisualCreateRelateModule, getVisualUpdateRelateModule } from '/@/api/module/module';
  export default defineComponent({
    name: 'RelateComponentDrawer',
    components: {
      BasicDrawer,
      BasicForm,
      Select,
      ConfigurationModal,
    },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      const isUpdate = ref(true);
      let dataRef = ref<Recordable>({});
      const formCode = ref('');
      const moduleCode = ref('');
      const moduleList = ref<Recordable[]>([]);
      const { createMessage } = useMessage();

      const [registerForm, { resetFields, setFieldsValue, validate, updateSchema }] = useForm({
        labelWidth: 90,
        schemas: formSchema,
        showActionButtonGroup: false,
      });

      const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
        setDrawerProps({ confirmLoading: false });
        isUpdate.value = data?.isUpdate;
        formCode.value = data?.formCode;
        moduleCode.value = data?.moduleCode;
        dataRef.value = data?.record ?? {};
        getFormGetFieldsData();

        getVisualGetFormFieldsWithModuleRelatedData();
        resetFields();
        if (unref(isUpdate)) {
          dataRef.value.formCode = formCode.value;
          dataRef.value.code = moduleCode.value;
          dataRef.value.relateCode = dataRef.value.moduleCode;
          dataRef.value.formCode = formCode.value;
          dataRef.value.field = dataRef.value.relateField;
          dataRef.value.is_on_tab = dataRef.value.is_on_tab == 1 ? true : false;
          updateSchema([
            {
              field: 'tabName',
              ifShow: true,
            },
          ]);
        } else {
          updateSchema([
            {
              field: 'tabName',
              ifShow: false,
            },
          ]);
        }
        setFieldsValue({
          ...dataRef.value,
        });
      });

      const getTitle = computed(() => (!unref(isUpdate) ? '新增' : '编辑'));

      const formGetFieldsData = ref([]);
      //获取数据
      const getFormGetFieldsData = () => {
        formGetFieldsData.value = [];
        try {
          if (!formCode.value) return;
          getFormGetFields({ formCode: formCode.value }).then((res) => {
            formGetFieldsData.value = res || [];
            formGetFieldsData.value.forEach((item: Recordable) => {
              delete item.options;
              item.value = item.name;
              item.label = item.title;
            });
          });
        } catch (err) {
          console.log('getFormGetFields', err);
        }
      };

      const formFieldsWithModuleRelatedList = ref([]);
      //获取模块数据
      const getVisualGetFormFieldsWithModuleRelatedData = async () => {
        formFieldsWithModuleRelatedList.value = [];
        try {
          if (!moduleCode.value) return;
          await getVisualGetFormFieldsWithModuleRelated({ moduleCode: moduleCode.value }).then(
            async (res) => {
              formFieldsWithModuleRelatedList.value = res || [];
              formFieldsWithModuleRelatedList.value.forEach((item: Recordable) => {
                item.label = item.name;
              });
            },
          );
        } catch (err) {
          console.log('getFormGetFields', err);
        }
      };
      //模块change
      const handleChangeRelateCode = (val) => {
        // console.log('handleChangeRelateCode', val);
        // dataRef.value['fieldRelated'] = '';
        // if (val) {
        //   getOtherFormGetFieldsData(val);
        // }
      };

      const moduleFormGetFieldsData = ref<Recordable[]>([]);
      const fieldRelatedList = ref<Recordable[]>([]);
      //获取模块的字段
      const getOtherFormGetFieldsData = (val) => {
        moduleFormGetFieldsData.value = [];
        try {
          if (!val) return;
          getFormGetFields({ formCode: val }).then((res) => {
            moduleFormGetFieldsData.value = res || [];
            moduleFormGetFieldsData.value.forEach((item: Recordable) => {
              delete item.options;
              item.value = item.name;
              item.label = item.title;
            });
            fieldRelatedList.value = [...moduleFormGetFieldsData.value, ...otherFormFields];
          });
        } catch (err) {
          console.log('getOtherFormGetFieldsData', err);
        }
      };

      const [registerConfigurationModal, { openModal: openConfiguration }] = useModal();
      //组合条件配置
      const handleConfiguration = () => {
        openConfiguration(true, {
          list: dataRef.value.conds || [],
          formGetFieldsData: formGetFieldsData.value,
        });
      };

      const handleSuccessConfigurationModal = ({ value }) => {
        dataRef.value.conds = value;
        setFieldsValue({ conds: value });
      };

      async function handleSubmit() {
        try {
          console.log('handleSubmit dataRef', dataRef.value);
          const values = await validate();
          let formData = Object.assign({}, dataRef.value, values);
          formData.code = moduleCode.value;
          if (formData.is_on_tab) {
            formData.is_on_tab = 1;
          } else {
            delete formData.is_on_tab;
          }
          setDrawerProps({ confirmLoading: true });
          if (!unref(isUpdate)) {
            formData.formCode = formCode.value;
            formData.relateCodeSel = formData.relateCode;
            formData.field = 'id';
            console.log('formData', formData);
            await getVisualCreateRelateModule(formData);
          } else {
            console.log('formData', formData);
            await getVisualUpdateRelateModule(formData);
          }
          createMessage.success('操作成功');
          closeDrawer();
          emit('success');
        } finally {
          setDrawerProps({ confirmLoading: false });
        }
      }
      const fetch = async () => {
        moduleList.value = (await getModulesAll()) || [];
      };

      onMounted(fetch);

      return {
        registerDrawer,
        registerForm,
        getTitle,
        handleSubmit,
        isUpdate,
        registerConfigurationModal,
        handleSuccessConfigurationModal,
        handleConfiguration,
        dataRef,
        handleChangeRelateCode,
        formFieldsWithModuleRelatedList,
        formGetFieldsData,
        moduleFormGetFieldsData,
        moduleList,
      };
    },
  });
</script>
